# Created by james at 20200908
# react antd 选择器 封装
from robot.api import logger
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

from .antd_page_element import AntdPageElement
from ...common.element_function import ElementFunction
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Select(AntdPageElement):

    def setValue(self, *values):
        self.wait_element_presence()
        self.wait_element_ready()
        # 清除之前的选择
        self._clear()
        # 点击
        ElementFunction(self._driver).click(self._get_web_element())

        for value in values:
            item_element = self._find_item(value)
            if item_element is None:
                raise TestException.by_error_code(ErrorCode.COMBOTREE_VALUE_NOT_EXIST, value=value)
            item_element.click()

        # 当前选择框需要失去焦点，不然多选的选择框还在, 用blur没效果
        ElementFunction(self._driver).send_keys('\t')

    def _find_item(self, value: str):
        selector_template_old = '//div[contains(@class,"ant-select-dropdown") and not(contains(@class,"ant-select-dropdown-hidden"))]' \
                            '//ul[@role="listbox"]' \
                            '//li[contains(@class,"ant-select-dropdown-menu-item") and text()="{0}"]'
        selector_template_new = '//div[contains(@class,"ant-select-dropdown") and not(contains(@class,"ant-select-dropdown-hidden"))]//div[@class="ant-select-item-option-content" and text()="{}"]'
        selector_template_list = [selector_template_new, selector_template_old]
        for selector_template in selector_template_list:
            selector = selector_template.format(value)
            element = ElementFunction(self._driver).try_find_element_in_page(selector)
            if element:
                return element
        logger.error('Can not find the list item:{0}'.format(selector))

    def _clear(self):
        selector = 'span.ant-select-selection__choice__remove'
        clear_elements = self._get_web_element().find_elements(By.CSS_SELECTOR, selector)
        for element in clear_elements:
            element.click()

    def get_identification(self):
        identification = {'class': ['ant-select', 'ant-select-dropdown']}
        return identification
